package com.bawei.library_base.utils.bitmap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

/**
 * @author : zhiyu
 * @date : 2021/12/12
 * @content :网络上获取
 */
public class NetUtils {
    //TODO 获取网络图片
    public static Bitmap getBitmap(String url) throws ExecutionException, InterruptedException {
        return new MyTask().execute(url).get();//get方法获取执行完毕返回的结果Bitmap对象
    }

    static class MyTask extends AsyncTask<String,String,Bitmap> {
        @Override
        protected Bitmap doInBackground(String... strings) {
            String imageUrl = strings[0];
            HttpURLConnection conn = null;
            try {
                URL url = new URL(imageUrl);
                conn = (HttpURLConnection) url.openConnection(); // 打开连接
                conn.setReadTimeout(5000); // 设置读取超时时间
                conn.setConnectTimeout(5000); // 设置连接超时时间
                conn.setRequestMethod("GET"); // 设置请求方式
                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream(); // 获取流数据
                    Bitmap bitmap = BitmapFactory.decodeStream(is); // 将流数据转成Bitmap对象
                    return bitmap;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    conn.disconnect(); // 断开连接
                }
            }
            return null;
        }
    }

}
